package com.qf.springbootopenapi.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.springbootopenapi.dao.ApiDao;
import com.qf.springbootopenapi.entity.Api;
import com.qf.springbootopenapi.service.ApiService;
import com.qf.springbootopenapi.utils.Constants;
import com.qf.springbootopenapi.vo.ResultVo;
import com.qf.springbootopenapi.vo.TableVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class ApiServiceImpl implements ApiService {
    
    @Autowired
    private ApiDao apiDao;
    
    
    @Override
    public TableVo<Api> getApiByCondition(Integer page, Integer limit, Api api) {
        PageHelper.startPage(page, limit);
        List<Api> data = apiDao.getApiByCondition(api);
    
        long total = new PageInfo<>(data).getTotal();
    
        return TableVo.ok((int) total, data);
    }
    
    @Override
    public ResultVo addApi(Api api) {
        log.debug("保存的用户信息为：api={}", api);
    
        System.out.println(api);
    
        Integer integer = apiDao.insertApi(api);
    
        if (integer == 1) {
            return new ResultVo(Constants.SUCCESS_CODE, "接口添加成功！");
        } else {
            return new ResultVo(Constants.FAIL_CODE, "接口添加失败！");
        }
    }
    
    @Override
    public ResultVo updateApi(Api api) {
        log.debug("保存的用户信息为：api={}", api);
    
        Integer integer = apiDao.updateApiById(api);
    
        if (integer == 1) {
            return new ResultVo(Constants.SUCCESS_CODE, "接口更新成功！");
        } else {
            return new ResultVo(Constants.FAIL_CODE, "接口更新失败！");
        }
    }
    
    @Override
    public ResultVo delApi(Integer[] ids) {
        Integer integer = apiDao.delApiByIds(ids);
    
        if (integer != 0) {
            return new ResultVo(Constants.SUCCESS_CODE, "接口删除成功！");
        } else {
            return new ResultVo(Constants.FAIL_CODE, "接口删除失败！");
        }
    }
    
    
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultVo addApis(MultipartFile file) throws IOException {
    
        InputStream is = file.getInputStream();
    
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
    
        List<Api> apis = new ArrayList<>();
    
        String data;
    
        while ((data = br.readLine()) != null) {
            Api api = Api.cvsToApi(data);
            apis.add(api);
        }
        
        br.close();
        
        apiDao.insertApis(apis);
        
        return new ResultVo(Constants.SUCCESS_CODE, "插入成功！");
        
    }
}
